<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import {addEmployeeBatch} from '@/api/employees'
import {formatExcelDate} from '@/utils/index'
export default {
  name: 'Import',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    //上传之前的回调函数，限制上传文件的大小，上传的文件必须小于1M
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    //1.将excel文件中的数据读取出来转化为js数据
    handleSuccess({results,header}){
        this.tableData=results
        this.tableHeader=header
        console.log(results,'results');
        console.log(header,'header');
        // 2.中转英
        const data=this.transToExcel(results)
        console.log('data',data);

        // 3.发送ajax请求批量添加数据
        this.doAdd(data)
    },
    // 实现批量导入
    async doAdd(data){
        try {
            const res=await addEmployeeBatch(data)
            console.log('reseseses',res);
            // 回到原来的页面
            this.$router.back()
        } catch (error) {
            console.log(error);
        }
    },
    transToExcel(data){
        const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }

      const result=data.map(zhObj=>{
        // zhObj=>{
        //     '入职日期': '44505',
        //     '手机号': '1221',
        //     '姓名': '4456',
        //     '转正日期': '45343',
        //     '工号': '9002',
        //     '部门': 'd4545',
        // }
        const zhkeys= Object.keys(zhObj)//['入职日期','手机号'.....]
        const enkeyObj={} //存储英文key的对象数据
        zhkeys.forEach(zhkey=>{
                        //取key的值
            const enkey=mapInfo[zhkey]//enkey=> timeOfEntry
            if (enkey==='timeOfEntry' || enkey==='correctionTime') {
                enkeyObj[enkey]=formatExcelDate(zhObj[zhkey])
            } else {
                enkeyObj[enkey]=zhObj[zhkey]
            }
        })
        return enkeyObj
      })

      return result
    }
  }
}
</script>
